<?php

namespace app\common\model;

use app\common\model\Drug as DrugModel;
use think\Paginator;

class MedicationReminder extends BaseModel
{
    protected $name = "medication_reminder";

    /**
     * 获取数据列表
     * @param array $where 条件
     * @param string $field 字段
     * @return Paginator
     */
    public function getList(array $where=[], string $field="*"): Paginator
    {
        $medication_cycle = config('dictionary.medication_cycle');
        $reminder_frequency = config('dictionary.reminder_frequency');
        return $this->where($where)
                    ->field($field)
                    ->order('_id', 'desc')
                    ->paginate($this->pageLimit)
                    ->each(function ($item, $key) use($medication_cycle,$reminder_frequency) {

                        //药品分类
                        $type_value = (new DrugModel())->where('code', $item['drug_code'])->field('type_value')->find();
                        $item['type_value'] = $type_value['type_value']??'';

                        //提醒周期
                        if (!empty($medication_cycle[$item['cycle_unit']])) {
                            $item['cycle_text'] = $item['cycle'].$medication_cycle[$item['cycle_unit']];
                        }else{
                            $item['cycle_text'] = '';
                        }

                        //提醒频次
                        if (!empty($reminder_frequency[$item['frequency']])) {
                            $item['frequency_text'] = $reminder_frequency[$item['frequency']];
                        }else{
                            $item['frequency_text'] = '';
                        }

                        //服用时间
                        $take_time = '';
                        if (!empty($item['take_time'])) {
                            foreach ($item['take_time'] as $k => $v) {
                                $take_time .= $v['take_time_value'].',';
                            }
                            $item['take_time_text'] = rtrim($take_time, ',');
                        }else{
                            $item['take_time_text'] = '';
                        }
                        return $item;
                    });
    }

    /**
     * 添加数据
     * @param array $data
     * @return string
     */
    public function addData(array $data): string
    {
        //添加时销毁自带的主键id
        unset($data['id']);
        return $this->save($data);
    }

    /**
     * 更新数据
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        return $model->save($data);
    }
}